import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:znmm/config/app_color.dart';

/*

CustomTextField 更适合需要图标、清除按钮、密码隐藏等功能的复杂输入场景，比如登录界面或密码设置页面。

CustomTextField：更高级，支持带图标或自定义前缀图标、可选择隐藏输入（密码）、自定义填充色，
并带有完整的边框样式选择。适合在登录界面或具有自定义设计需求的输入场景使用。


CustomTextField(
          labelText: '请输入您的用户名',
          strText: _userNameStr,
          imageIcon: "assets/images/icons/account.png",
          bHasFrame: false,
          onInputComplete: (value) {
            //print("用户名:$value");
            _userNameStr = value;
            if (_glKey.currentState != null) {
              bool bEnable = value.isNotEmpty;
              _glKey.currentState!.setEnable(bEnable);
            }
          },
        )


*/

class CustomTextField extends StatefulWidget {
  final ValueChanged<String> onInputComplete;
  final IconData icon;
  final String imageIcon;
  final String labelText;
  final bool bHasHidIcon;
  final double fHeight;
  final String strText;
  final bool bHasFrame;

  const CustomTextField({
    Key? key,
    required this.labelText,
    required this.onInputComplete,
    this.icon = Icons.person,
    this.bHasHidIcon = false,
    this.bHasFrame = true,
    this.fHeight = 53.0,
    this.strText = "",
    this.imageIcon = "",
  }) : super(key: key);

  @override
  // ignore: library_private_types_in_public_api
  CustomTextFieldState createState() => CustomTextFieldState();
}

class CustomTextFieldState extends State<CustomTextField> {
  final TextEditingController _controller = TextEditingController();
  final FocusNode _focusNode = FocusNode(); // 添加一个 FocusNode

  bool _isObscured = true;

  @override
  void initState() {
    super.initState();

    if (widget.strText.isNotEmpty) {
      _controller.text = widget.strText;
    }

    // 监听焦点变化
    _focusNode.addListener(() {
      if (!_focusNode.hasFocus) {
        // 如果失去焦点，收起键盘
        FocusScope.of(context).unfocus();
        setState(() {
          widget.onInputComplete(_controller.text);
        });
      }
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  String getText() {
    String contantStr = _controller.text;
    _controller.clear();
    FocusScope.of(context).unfocus(); // 收起键盘
    return contantStr;
  }

  void setText(String text) {
    setState(() {
      _controller.text = text;
    });
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: widget.fHeight,
      child: TextFormField(
        controller: _controller,
        obscureText: widget.bHasHidIcon ? _isObscured : false,
        focusNode: _focusNode,
        onChanged: (value) {
          widget.onInputComplete(_controller.text);
        },
        decoration: InputDecoration(
          labelText: widget.labelText,
          labelStyle: TextStyle(color: AppColor.grey97999B),

          //floatingLabelBehavior: FloatingLabelBehavior.never, // 标签不会浮动
          filled: true,
          //isCollapsed: true,
          fillColor: widget.bHasFrame ? AppColor.white : AppColor.greyF3F4F8,
          prefixIconConstraints: BoxConstraints(
            maxHeight: 25.w,
          ), //prefixIcon约束
          border: widget.bHasFrame
              ? const OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.grey, // 边框颜色
                    width: 0.5, // 边框宽度
                  ),
                )
              : OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10),
                  borderSide: BorderSide.none,
                ),

          focusedBorder: widget.bHasFrame
              ? const OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.grey, width: 0.5),
                )
              : null,
          enabledBorder: widget.bHasFrame
              ? const OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.grey, width: 0.5),
                )
              : null,
          prefixIcon: widget.imageIcon.isEmpty
              ? Padding(
                  padding: EdgeInsets.symmetric(horizontal: 10.w),
                  child: Icon(
                    widget.icon,
                    color: Colors.grey,
                  ))
              : Padding(
                  padding: EdgeInsets.symmetric(horizontal: 10.w),
                  child: Image.asset(
                    widget.imageIcon,
                  )),

          suffixIcon: _controller.text.isNotEmpty
              ? (widget.bHasHidIcon
                  ? Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        IconButton(
                          icon: Icon(
                            Icons.clear,
                            color: Colors.grey.withOpacity(0.5),
                          ),
                          onPressed: () {
                            setState(() {
                              _controller.clear();
                              widget.onInputComplete(_controller.text);
                            });
                          },
                        ),
                        IconButton(
                          splashColor: Colors.transparent, // 点击时的波纹颜色设为透明
                          highlightColor: Colors.transparent, // 点击时的高亮颜色设为透明
                          icon: Icon(
                            _isObscured
                                ? Icons.visibility
                                : Icons.visibility_off,
                            color: Colors.grey.withOpacity(0.5),
                          ),
                          onPressed: () {
                            setState(() {
                              _isObscured = !_isObscured;
                            });
                          },
                        ),
                      ],
                    )
                  : IconButton(
                      icon: Icon(
                        Icons.clear,
                        color: Colors.grey.withOpacity(0.5),
                      ),
                      onPressed: () {
                        setState(() {
                          _controller.clear();
                          widget.onInputComplete(_controller.text);
                        });
                      },
                    ))
              : (widget.bHasHidIcon
                  ? IconButton(
                      splashColor: Colors.transparent, // 点击时的波纹颜色设为透明
                      highlightColor: Colors.transparent, // 点击时的高亮颜色设为透明
                      icon: Icon(
                        _isObscured ? Icons.visibility : Icons.visibility_off,
                        color: Colors.grey.withOpacity(0.5),
                      ),
                      onPressed: () {
                        setState(() {
                          _isObscured = !_isObscured;
                        });
                      },
                    )
                  : null),
        ),
      ),
    );
  }
}
